(function() {
    var connect = function() {
        window.socket = new WebSocket("ws://"+location.host+"/websocket", "computer.play-ios");

        window.addEvent("domready", function() {
            var body = document.id(document.body);
            var pairingnumber = document.id("pairingnumber");

            if(!Browser.Features.websockets) {
                body.set("class", "nowebsockets");
            }

            socket.addEvents({
                open: function() {
                    body.set("class", "unpaired");
                },
                message: function(e) {
                    var message = e.data;
                    if(message == "/Unpaired") {
                        body.set("class", "unpaired");
                    } else if(message == "/Paired") {
                        body.set("class", "paired");
                        pairingnumber.set("text", "");
                    } else if(message.indexOf("/PairingNumber:") == 0) {
                        pairingnumber.set("text", message.substr(15));
                    }
                },
                close: function() {
                    body.set("class", "noconnection");
                }
            });
        });
    };
    connect();

    window.addEvent("domready", function() {
        document.id("reconnect").addEvent("click", connect);
    });
})();